package main

import (
	"github.com/go-fsnotify/fsnotify"
	"ktvserver/config"
	"ktvserver/ktvutil"
	"ktvserver/ktvutil/videopath"
	"log"
	"strings"
	"time"
)

var (
	myWatcherDone = make(chan bool) // wathcer
)

// 监听系统文件修改清空
func EnableWatherSystemDirectory() {

	if ktvutil.FileExists("SYSTEM") != true {
		log.Println("SYSTEM directory is not found!")
		return
	}

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Println("error:", err)
		return
	}
	defer watcher.Close()

	go func() {
		for {
			select {
			case event := <-watcher.Events:
				log.Println("event:", event)
				//if event.Op&fsnotify.Write == fsnotify.Write {
				//log.Println("modified file:", event.Name)
				// 1)歌曲视频文件路径
				if strings.EqualFold(event.Name, videopath.VideoPathDataFile) {
					go func() {
						// 休眠5秒钟再加载
						time.Sleep(time.Second * 5)
						videopath.ReloadSongVideoPath()
					}()

				}
				//2) 系统配置文件
				if strings.EqualFold(event.Name, config.KtvConfigFilePath) {
					go func() {
						// 休眠5秒钟再加载
						time.Sleep(time.Second * 5)
						config.ReloadConfig()
					}()

				}

				//}
			case err := <-watcher.Errors:
				log.Println("error:", err)
			}
		}
	}()

	err = watcher.Add("SYSTEM")
	if err != nil {
		log.Println("error:", err)
		return
	}

	<-myWatcherDone

}
